<template>
  <div class="equipment-maintenance">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="维护单号">
          <el-input v-model="searchForm.maintenanceNo" placeholder="请输入维护单号" clearable />
        </el-form-item>
        <el-form-item label="维护类型">
          <el-select v-model="searchForm.maintenanceType" placeholder="请选择维护类型" clearable>
            <el-option 
              v-for="item in maintenanceTypeList" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="维护状态">
          <el-select v-model="searchForm.status" placeholder="请选择维护状态" clearable>
            <el-option 
              v-for="item in maintenanceStatusList" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="operation-area">
      <el-button type="primary" @click="handleAdd">新增维护</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
      >
        <el-table-column prop="maintenanceNo" label="维护单号" width="150" />
        <el-table-column prop="deviceName" label="设备名称" min-width="150" />
        <el-table-column prop="deviceNo" label="设备编号" width="150" />
        <el-table-column prop="maintenanceTypeName" label="维护类型" width="120" />
        <el-table-column prop="statusName" label="维护状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ scope.row.statusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="planStartTime" label="计划开始时间" width="150">
          <template #default="scope">
            {{ formatDateTime(scope.row.planStartTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="planEndTime" label="计划结束时间" width="150">
          <template #default="scope">
            {{ formatDateTime(scope.row.planEndTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="maintainer" label="维护人员" width="100" />
        <el-table-column prop="maintenanceCost" label="维护费用" width="120">
          <template #default="scope">
            {{ formatPrice(scope.row.maintenanceCost) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="150">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="success" size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button 
              v-if="scope.row.status === 0" 
              type="warning" 
              size="small" 
              @click="handleStart(scope.row)"
            >
              开始维护
            </el-button>
            <el-button 
              v-if="scope.row.status === 1" 
              type="success" 
              size="small" 
              @click="handleComplete(scope.row)"
            >
              完成维护
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-area">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备" prop="deviceId">
              <el-select 
                v-model="form.deviceId" 
                placeholder="请选择设备" 
                style="width: 100%"
                filterable
                @change="handleDeviceChange"
              >
                <el-option 
                  v-for="item in deviceList" 
                  :key="item.id" 
                  :label="`${item.deviceName} (${item.deviceNo})`" 
                  :value="item.id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维护类型" prop="maintenanceType">
              <el-select v-model="form.maintenanceType" placeholder="请选择维护类型" style="width: 100%">
                <el-option 
                  v-for="item in maintenanceTypeList" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划开始时间" prop="planStartTime">
              <el-date-picker
                v-model="form.planStartTime"
                type="datetime"
                placeholder="请选择计划开始时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划结束时间">
              <el-date-picker
                v-model="form.planEndTime"
                type="datetime"
                placeholder="请选择计划结束时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="维护人员">
              <el-input v-model="form.maintainer" placeholder="请输入维护人员" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维护费用">
              <el-input-number
                v-model="form.maintenanceCost"
                :precision="2"
                :step="100"
                :min="0"
                style="width: 100%"
                placeholder="请输入维护费用"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="维护内容" prop="maintenanceContent">
          <el-input
            v-model="form.maintenanceContent"
            type="textarea"
            :rows="3"
            placeholder="请输入维护内容"
          />
        </el-form-item>
        <el-form-item label="故障描述">
          <el-input
            v-model="form.faultDescription"
            type="textarea"
            :rows="2"
            placeholder="请输入故障描述"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 维护详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="维护详情"
      width="60%"
      :close-on-click-modal="false"
    >
      <div v-if="maintenanceDetail" class="maintenance-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="维护单号">{{ maintenanceDetail.maintenanceNo }}</el-descriptions-item>
          <el-descriptions-item label="设备名称">{{ maintenanceDetail.deviceName }}</el-descriptions-item>
          <el-descriptions-item label="设备编号">{{ maintenanceDetail.deviceNo }}</el-descriptions-item>
          <el-descriptions-item label="维护类型">{{ maintenanceDetail.maintenanceTypeName }}</el-descriptions-item>
          <el-descriptions-item label="维护状态">
            <el-tag :type="getStatusTagType(maintenanceDetail.status)">
              {{ maintenanceDetail.statusName }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="维护人员">{{ maintenanceDetail.maintainer || '无' }}</el-descriptions-item>
          <el-descriptions-item label="计划开始时间">{{ formatDateTime(maintenanceDetail.planStartTime) }}</el-descriptions-item>
          <el-descriptions-item label="计划结束时间">{{ formatDateTime(maintenanceDetail.planEndTime) }}</el-descriptions-item>
          <el-descriptions-item label="实际开始时间">{{ formatDateTime(maintenanceDetail.actualStartTime) }}</el-descriptions-item>
          <el-descriptions-item label="实际结束时间">{{ formatDateTime(maintenanceDetail.actualEndTime) }}</el-descriptions-item>
          <el-descriptions-item label="维护费用">{{ formatPrice(maintenanceDetail.maintenanceCost) }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(maintenanceDetail.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="维护内容" :span="2">{{ maintenanceDetail.maintenanceContent || '无' }}</el-descriptions-item>
          <el-descriptions-item label="维护结果" :span="2">{{ maintenanceDetail.maintenanceResult || '无' }}</el-descriptions-item>
          <el-descriptions-item label="故障描述" :span="2">{{ maintenanceDetail.faultDescription || '无' }}</el-descriptions-item>
          <el-descriptions-item label="解决方案" :span="2">{{ maintenanceDetail.solution || '无' }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ maintenanceDetail.remark || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 完成维护对话框 -->
    <el-dialog
      v-model="completeDialogVisible"
      title="完成维护"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-form :model="completeForm" :rules="completeRules" ref="completeFormRef" label-width="120px">
        <el-form-item label="维护结果" prop="maintenanceResult">
          <el-input
            v-model="completeForm.maintenanceResult"
            type="textarea"
            :rows="3"
            placeholder="请输入维护结果"
          />
        </el-form-item>
        <el-form-item label="维护费用" prop="maintenanceCost">
          <el-input-number
            v-model="completeForm.maintenanceCost"
            :precision="2"
            :step="100"
            :min="0"
            style="width: 100%"
            placeholder="请输入维护费用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="completeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCompleteSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { equipmentApi } from '@/api/equipment/equipment'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: "equipment_maintenance",
  data() {
    return {
      // 搜索表单
      searchForm: {
        maintenanceNo: '',
        maintenanceType: '',
        status: ''
      },
      // 表格数据
      tableData: [],
      // 加载状态
      loading: false,
      // 分页信息
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      // 对话框显示状态
      dialogVisible: false,
      // 对话框标题
      dialogTitle: '',
      // 表单数据
      form: {
        deviceId: null,
        maintenanceType: null,
        planStartTime: '',
        planEndTime: '',
        maintainer: '',
        maintenanceCost: null,
        maintenanceContent: '',
        faultDescription: '',
        remark: ''
      },
      // 表单验证规则
      rules: {
        deviceId: [
          { required: true, message: '请选择设备', trigger: 'change' }
        ],
        maintenanceType: [
          { required: true, message: '请选择维护类型', trigger: 'change' }
        ],
        planStartTime: [
          { required: true, message: '请选择计划开始时间', trigger: 'change' }
        ],
        maintenanceContent: [
          { required: true, message: '请输入维护内容', trigger: 'blur' }
        ]
      },
      // 表单引用
      formRef: null,
      // 编辑模式
      isEdit: false,
      // 编辑的维护ID
      editId: null,
      // 详情对话框
      detailDialogVisible: false,
      // 维护详情数据
      maintenanceDetail: null,
      // 完成维护对话框
      completeDialogVisible: false,
      // 完成维护表单
      completeForm: {
        maintenanceResult: '',
        maintenanceCost: null
      },
      // 完成维护验证规则
      completeRules: {
        maintenanceResult: [
          { required: true, message: '请输入维护结果', trigger: 'blur' }
        ]
      },
      // 完成维护表单引用
      completeFormRef: null,
      // 当前操作的维护ID
      currentMaintenanceId: null,
      // 维护类型列表
      maintenanceTypeList: [
        { value: 1, label: '日常保养' },
        { value: 2, label: '定期维护' },
        { value: 3, label: '故障维修' },
        { value: 4, label: '大修' }
      ],
      // 维护状态列表
      maintenanceStatusList: [
        { value: 0, label: '待维护' },
        { value: 1, label: '维护中' },
        { value: 2, label: '已完成' },
        { value: 3, label: '已取消' }
      ],
      // 设备列表
      deviceList: []
    }
  },
  mounted() {
    this.loadTableData()
    this.loadDeviceList()
  },
  methods: {
    // 加载表格数据
    async loadTableData() {
      this.loading = true
      try {
        const params = {
          ...this.searchForm,
          current: this.pagination.current,
          size: this.pagination.size
        }
        const res = await equipmentApi.getDeviceMaintenancePage(params)
        if (res.code === 200) {
          this.tableData = res.data.records
          this.pagination.total = res.data.total
        }
      } catch (error) {
        console.error('加载表格数据失败:', error)
        ElMessage.error('加载数据失败')
      } finally {
        this.loading = false
      }
    },

    // 加载设备列表
    async loadDeviceList() {
      try {
        const res = await equipmentApi.getDevicePage({ current: 1, size: 1000 })
        if (res.code === 200) {
          this.deviceList = res.data.records
        }
      } catch (error) {
        console.error('加载设备列表失败:', error)
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.current = 1
      this.loadTableData()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        maintenanceNo: '',
        maintenanceType: '',
        status: ''
      }
      this.handleSearch()
    },

    // 新增维护
    handleAdd() {
      this.isEdit = false
      this.editId = null
      this.dialogTitle = '新增维护'
      this.form = {
        deviceId: null,
        maintenanceType: null,
        planStartTime: '',
        planEndTime: '',
        maintainer: '',
        maintenanceCost: null,
        maintenanceContent: '',
        faultDescription: '',
        remark: ''
      }
      this.dialogVisible = true
    },

    // 编辑维护
    handleEdit(row) {
      this.isEdit = true
      this.editId = row.id
      this.dialogTitle = '编辑维护'
      this.form = {
        deviceId: row.deviceId,
        maintenanceType: row.maintenanceType,
        planStartTime: row.planStartTime,
        planEndTime: row.planEndTime,
        maintainer: row.maintainer,
        maintenanceCost: row.maintenanceCost,
        maintenanceContent: row.maintenanceContent,
        faultDescription: row.faultDescription,
        remark: row.remark
      }
      this.dialogVisible = true
    },

    // 保存维护
    async handleSave() {
      try {
        await this.$refs.formRef.validate()
        
        if (this.isEdit) {
          // 编辑
          const res = await equipmentApi.updateDeviceMaintenance(this.editId, this.form)
          if (res.code === 200) {
            ElMessage.success('维护记录更新成功')
            this.dialogVisible = false
            this.loadTableData()
          } else {
            ElMessage.error(res.message || '更新失败')
          }
        } else {
          // 新增
          const res = await equipmentApi.addDeviceMaintenance(this.form)
          if (res.code === 200) {
            ElMessage.success('维护记录创建成功')
            this.dialogVisible = false
            this.loadTableData()
          } else {
            ElMessage.error(res.message || '创建失败')
          }
        }
      } catch (error) {
        console.error('保存失败:', error)
      }
    },

    // 查看详情
    async handleView(row) {
      try {
        const res = await equipmentApi.getDeviceMaintenanceById(row.id)
        if (res.code === 200) {
          this.maintenanceDetail = res.data
          this.detailDialogVisible = true
        } else {
          ElMessage.error(res.message || '获取维护详情失败')
        }
      } catch (error) {
        console.error('获取维护详情失败:', error)
        ElMessage.error('获取维护详情失败')
      }
    },

    // 开始维护
    async handleStart(row) {
      try {
        await ElMessageBox.confirm('确定要开始维护吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const res = await equipmentApi.startMaintenance(row.id)
        if (res.code === 200) {
          ElMessage.success('维护已开始')
          this.loadTableData()
        } else {
          ElMessage.error(res.message || '开始维护失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('开始维护失败:', error)
          ElMessage.error('开始维护失败')
        }
      }
    },

    // 完成维护
    handleComplete(row) {
      this.currentMaintenanceId = row.id
      this.completeForm = {
        maintenanceResult: '',
        maintenanceCost: null
      }
      this.completeDialogVisible = true
    },

    // 保存完成维护
    async handleCompleteSave() {
      try {
        await this.$refs.completeFormRef.validate()
        
        const res = await equipmentApi.completeMaintenance(this.currentMaintenanceId, this.completeForm)
        if (res.code === 200) {
          ElMessage.success('维护已完成')
          this.completeDialogVisible = false
          this.loadTableData()
        } else {
          ElMessage.error(res.message || '完成维护失败')
        }
      } catch (error) {
        console.error('完成维护失败:', error)
      }
    },

    // 删除维护
    async handleDelete(row) {
      try {
        await ElMessageBox.confirm('确定要删除该维护记录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const res = await equipmentApi.deleteDeviceMaintenance(row.id)
        if (res.code === 200) {
          ElMessage.success('删除成功')
          this.loadTableData()
        } else {
          ElMessage.error(res.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      }
    },

    // 设备选择变化
    handleDeviceChange(deviceId) {
      // 可以在这里添加设备相关的逻辑
    },

    // 分页大小变化
    handleSizeChange(size) {
      this.pagination.size = size
      this.pagination.current = 1
      this.loadTableData()
    },

    // 当前页变化
    handleCurrentChange(current) {
      this.pagination.current = current
      this.loadTableData()
    },

    // 格式化日期时间
    formatDateTime(date) {
      if (!date) return ''
      return new Date(date).toLocaleString()
    },

    // 格式化价格
    formatPrice(price) {
      if (!price) return '0.00'
      return Number(price).toFixed(2)
    },

    // 获取状态标签类型
    getStatusTagType(status) {
      switch (status) {
        case 0:
          return 'info'
        case 1:
          return 'warning'
        case 2:
          return 'success'
        case 3:
          return 'danger'
        default:
          return 'info'
      }
    }
  }
}
</script>

<style scoped>
.equipment-maintenance {
  padding: 20px;
}

.search-area {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.operation-area {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-area {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-area {
  margin-top: 20px;
  text-align: right;
}

.search-form .el-form-item {
  margin-bottom: 15px;
}

.dialog-footer {
  text-align: right;
}

.maintenance-detail .el-descriptions {
  margin-bottom: 20px;
}
</style>
